﻿Imports Microsoft.VisualBasic

Namespace MyApp
    Namespace Network

        Public Class Twitter

            Public Property oauth As WebApi.Oauth.Oauth
            Public Property HttpContextCurrent() As HttpContext

            Private IsUserAccount As Boolean = False

            Private db As mDB = mDB.GetDB

            'Public Function GetUserAccountAvailable(s As mDB.User_Account.ServiceType) As mDB.User_Account
            '    Dim FieldLastRate = mDB.User_Account.GetFieldService(s)

            '    Dim userAcc = db.TAB.User_Account.
            '        Where(FieldLastRate, "<", Date.UtcNow.AddMinutes(-15)).
            '        OrderBy(FieldLastRate).
            '        Limit(1).
            '    ToObj

            '    Return userAcc

            'End Function

            Public Sub New()


            End Sub

            Public Sub New(oauth As WebApi.Oauth.Oauth)

                Me.oauth = oauth

            End Sub


            Public Function RedirectAuth() As String

                oauth.getResponse("https://api.twitter.com/oauth/request_token")

                'Redirigo l'utente a twitter che ha capito chi sono e verifica se l'utente è loggato e se sì controlla che abbia l'autorizzazione con la mia applicazione
                Return "https://api.twitter.com/oauth/authenticate?oauth_token=" & oauth.oauthToken

            End Function

            Public Sub AddLogin(oauth_token As String, oauth_verifier As String)
                Dim db = mDB.GetDB
                Dim CurrUser = MyApp.GetUser(False)

                'L'utente riconosciuto da Twitter ci ha autorizzato, chiedo quindi a Twitter i dati dell'utente
                oauth.oauthToken = oauth_token
                oauth.oauthVerifier = oauth_verifier
                oauth.getResponse("https://api.twitter.com/oauth/access_token")

                Dim tc = New WebApi.Twitter.TwitterClient(oauth)

                Dim tu = tc.GetUserShow("", oauth.returnedParams("user_id"))

                '--------------------------------------------
                ' creo account

                Dim acc = Me.UpdateAccount(tu)

                '--------------------------------------------
                ' creo account_update

                Dim acc_update = acc.Account_Update

                '--------------------------------------------
                ' creo account_auth

                Dim AccAuth = acc.Account_Auth ' CurrUser.tab_acc Tab_UserAccount.BY.User_Account.Account_Id(acc.Id).Limit(1).ToObj
                If AccAuth Is Nothing Then
                    AccAuth = New mDB.Account_Auth
                    db.TAB.Account_Auth.InsertOnSubmit(AccAuth)
                End If

                AccAuth.Account_Id = acc.Id
                AccAuth.Network_Id = MyApp.Network.AccType.TWITTER_ACCOUNT
                AccAuth.Oauth_Consumer_Key = oauth.oauthConsumerKey
                AccAuth.Oauth_Consumer_Secret = oauth.oauthConsumerSecret
                AccAuth.Oauth_Token = oauth.oauthToken
                AccAuth.Oauth_Token_Secret = oauth.oauthTokenSecret

                AccAuth.Error_Account_Last_Date = Date.MinValue
                AccAuth.Error_Account_Count = 0
                AccAuth.Disabled = 0

                '--------------------------------------------
                ' creo user_account

                Dim UserAcc = CurrUser.Tab_User_Account(acc.Id).ToObj
                If UserAcc Is Nothing Then
                    UserAcc = New mDB.User_Account
                    db.TAB.User_Account.InsertOnSubmit(UserAcc)
                End If

                UserAcc.User_Id = CurrUser.Id
                UserAcc.Account_Id = acc.Id

                db.SubmitChanges()


            End Sub

            'Public Sub SendPosts(t As String, ToAccounts As List(Of String), Direct As Boolean)

            '    Dim tc = New WebApi.Twitter.TwitterClient(Me.oauth)

            '    If ToAccounts IsNot Nothing Then
            '        For Each id In ToAccounts
            '            Me.SendPost(t, id, Direct)
            '        Next
            '    Else
            '        Me.SendPost(t, "", False)
            '    End If


            'End Sub

            'Public Function SendShareAccountPost(AccountId As Integer, LastPostCode As String) As mDB.Account_Post
            '    Dim tc = New WebApi.Twitter.TwitterClient(Me.oauth)
            '    Dim LastDate As Date = Date.MinValue

            '    If LastPostCode <> "" Then
            '        Dim LastPost = db.TAB.AccountPost.BY.AccountPost.PostCode(LastPostCode).ToObj
            '        If LastPost IsNot Nothing Then
            '            LastDate = LastPost.Pubb_Date
            '        End If
            '    End If

            '    Dim SharePosts = db.TAB.AccountPost.
            '        BY.AccountPost.Account_Id(AccountId).
            '        Where("Pubb_Date", ">=", LastDate).
            '        OrderBy("Pubb_Date desc").
            '        Limit(5).
            '    ToList()

            '    SharePosts = SharePosts.OrderBy(Function(o) o.Pubb_Date).ToList

            '    If SharePosts.Count > 0 Then
            '        MyApp.WriteProcLog(SF("(tab)(tab)begin share post account : {0}, post number: {1}", AccountId, SharePosts.Count), AutoProcType.SEND_POSTS)

            '        For Each p In SharePosts

            '            If p.Post_Code <> LastPostCode Then
            '                MyApp.WriteProcLog(SF("(tab)(tab)(tab)share post code: {0}", p.Post_Code), AutoProcType.SEND_POSTS)
            '                tc.PostReTweet(p.Post_Code)

            '                'Dim r = p.Post_Code

            '            End If

            '        Next

            '        Return SharePosts(SharePosts.Count - 1)

            '    Else
            '        Return Nothing
            '    End If
            '    'MyApp.WriteProcLog(SF("(tab)(tab)end share post account : {0}", AccountId), AutoProcType.SEND_POSTS)


            'End Function

#Region "POST SEND"

            Public Function SendPost(Acc As mDB.Account, Post As mDB.Task_Post) As WebApi.Twitter.Tweet

                Dim p As WebApi.Twitter.Tweet = Nothing
                Dim tc = New WebApi.Twitter.TwitterClient(Me.oauth)
                tc.AutoProc = Task.TaskType.SEND_POSTS

                MyApp.WriteProcLog(SF("(tab)(tab)send post : '{0}', to: {1}, type: {2}", Post.Post_Text, Post.To_Account_Username, Post.Post_Type_Id), Task.TaskType.SEND_POSTS)

                Select Case DirectCast(Post.Post_Type_Id, mDB.Task_Post.Type)
                    Case mDB.Task_Post.Type.NORMAL

                        Dim PostText = Post.Post_Text
                        If Post.To_Account_Username <> "" Then
                            PostText = SF("@{0} {1}", Post.To_Account_Username, Post.Post_Text)
                        End If

                        If Post.Media_Id = 0 Then
                            p = tc.PostTweet(PostText, Post.Reply_Post_Code, "", "")
                        Else
                            Dim Media = Post.Media
                            If Media.Display_Url <> "" Then
                                PostText &= " " & Media.Display_Url
                                p = tc.PostTweet(PostText, Post.Reply_Post_Code, "", "")
                            Else
                                p = tc.PostTweetMediaBase64(Post.Post_Text, Media.ToBase64)
                                If p IsNot Nothing Then
                                    Media.Display_Url = p.entities.media(0).display_url
                                    Media.Media_Url = p.entities.media(0).media_url
                                End If
                            End If

                        End If

                    Case mDB.Task_Post.Type.PRIVATE
                        p = tc.PostDirectMessage(Post.To_Account_Username, "", Post.Post_Text)
                        If p IsNot Nothing Then
                            Dim mess = Me.UpdatePrivatePost(Acc, p)

                        End If


                    Case mDB.Task_Post.Type.SHARE
                        p = tc.PostReTweet(Post.Share_Post_Code)


                        If p IsNot Nothing Then

                            Dim share = Me.UpdateSharePost(Acc, p.retweeted_status)
                            Me.UpdateSharePostDetail(share, p)

                            'Acc.AddPostShare(Post.Share_Post_Code, p.id_str)

                        End If


                End Select

                Return p
            End Function
            Public Function RemovePost(Acc As mDB.Account, PostCode As String, PosType As mDB.Task_Post.Type) As WebApi.Twitter.Tweet

                Dim p As WebApi.Twitter.Tweet = Nothing
                Dim tc = New WebApi.Twitter.TwitterClient(Me.oauth)
                tc.AutoProc = Task.TaskType.SEND_POSTS

                MyApp.WriteProcLog(SF("(tab)(tab)remove post : '{0}', type: {1}", PostCode, PosType), Task.TaskType.SEND_POSTS)

                p = tc.PostStatusesDestroy(PostCode)

                Select Case PosType
                    Case mDB.Task_Post.Type.NORMAL

                    Case mDB.Task_Post.Type.PRIVATE

                    Case mDB.Task_Post.Type.SHARE

                End Select

                Return p
            End Function
            'Public Function RemovePost2(Acc As mDB.Account, PostCode As mDB.Task_Post) As WebApi.Twitter.Tweet


            '    Dim p As WebApi.Twitter.Tweet = Nothing
            '    Dim tc = New WebApi.Twitter.TwitterClient(Me.oauth)
            '    tc.AutoProc = Task.TaskType.SEND_POSTS

            '    MyApp.WriteProcLog(SF("(tab)(tab)remove post : '{0}', to: {1}, type: {2}", Post.Post_Text, Post.To_Account_Username, Post.Post_Type_Id), Task.TaskType.SEND_POSTS)

            '    p = tc.PostStatusesDestroy(Post.Reply_Post_Code)

            '    Select Case DirectCast(Post.Post_Type_Id, mDB.Task_Post.Type)
            '        Case mDB.Task_Post.Type.NORMAL

            '        Case mDB.Task_Post.Type.PRIVATE

            '        Case mDB.Task_Post.Type.SHARE

            '            Acc.RemoveSharePost(Post.Reply_Post_Code)

            '    End Select

            '    Return p
            'End Function
            'Public Sub SendPost(t As String, ToAccountCode As String, Direct As Boolean)

            '    Dim tc = New WebApi.Twitter.TwitterClient(Me.oauth)

            '    MyApp.WriteProcLog(SF("(tab)(tab)send post : '{0}', to: {1}, direct: {2}", t, ToAccountCode, Direct), AutoProcType.SEND_POSTS)


            '    If ToAccountCode.Trim <> "" Then
            '        If Direct Then
            '            'tc.PostMessageToUser(ToAccountCode, "", t)
            '            tc.PostTweet(SF("D @{0} {1}", ToAccountCode, t))
            '        Else
            '            tc.PostTweet(SF("@{0} {1}", ToAccountCode, t))
            '        End If
            '    Else
            '        tc.PostTweet(t)
            '    End If

            'End Sub

#End Region

#Region "ACCOUNT"

            Public Function DownloadAccounts(usernames As List(Of String), userids As List(Of String)) As List(Of mDB.Account)
                Dim tc = New WebApi.Twitter.TwitterClient(Me.oauth)
                Dim NumUserPerRequest = 50
                Dim Accounts As New List(Of mDB.Account)
                Dim ids As List(Of String)

                If usernames IsNot Nothing Then
                    ids = usernames
                Else
                    ids = userids
                End If


                Dim page = Int((ids.Count - 1) / NumUserPerRequest) + 1

                For ct = 1 To page

                    Dim Numids = NumUserPerRequest
                    If ct = page Then
                        Numids = ids.Count - ((page - 1) * NumUserPerRequest)
                    End If

                    Dim tusers As List(Of WebApi.Twitter.User)
                    Dim IdsCurrent = ids.GetRange((ct - 1) * NumUserPerRequest, Numids)
                    Dim IdsLookup = String.Join(",", IdsCurrent)

                    Try

                        If usernames IsNot Nothing Then
                            tusers = tc.GetUsersLookup(IdsLookup, "")
                        Else
                            tusers = tc.GetUsersLookup("", IdsLookup)
                        End If

                        MyApp.WriteProcLog(SF("(tab)(tab)update number user: {0}", Numids), Task.TaskType.UPDATE_ACCOUNTS)

                        For Each tu In tusers

                            Dim Acc = Me.UpdateAccount(tu)
                            Accounts.Add(Acc)

                        Next

                        'Catch ex As WebApi.Net.ExceptionAPIAccount

                    Catch ex As WebApi.Net.ExceptionAPIResponse

                        'MyApp.WriteProcLog(SF("(tab)(tab)error update user: {0}, {1}", tc.LastError.Code, tc.LastError.Message), AutoProcType.UPDATE_ACCOUNTS)

                        'IMPORTANTE se tutti gli  utenti
                        Select Case tc.LastError.Code
                            Case 34, 17
                                MyApp.WriteProcLog(SF("(tab)(tab)account non exits: {0}", IdsLookup), Task.TaskType.UPDATE_ACCOUNTS)
                                Dim accids = db.TAB.Account.Where("account_code", "IN", IdsCurrent).ToList(Of Integer)("id")
                                If accids.Count > 0 Then
                                    db.TAB.Account_Add_Info.Where("account_id", "IN", accids).Update.UpdateValue("profile_update", Date.UtcNow.AddMonths(1)).ExecuteCommand()
                                End If
                        End Select


                        'Exit Do
                    End Try


                Next

                Return Accounts

            End Function
            Public Function UpdateAccount(tu As WebApi.Twitter.User) As mDB.Account


                '--------------------------------------------
                ' creo account
                Dim Acc = mDB.Account.GetForUpdate(tu.id_str, AccType.TWITTER_ACCOUNT)
                'db.SubmitChanges()

                'Dim Acc = db.TAB.Account.BY.Account.Account_Code(tu.id_str).ToObj

                'If Acc Is Nothing Then
                '    Acc = (New mDB.Account).SetDefault
                '    Acc.Network_Id = App.NetworkType.TWITTER
                '    Acc.Account_Code = tu.id_str

                '    Acc.InsertOnSubmit(db)
                'End If

                Acc.Fullname = tu.name
                Acc.Username = tu.screen_name
                Acc.Avatar = Mid(tu.profile_image_url, 1, 255)
                Acc.Location = tu.location
                Acc.Joined_Date = tu.created_at
                Acc.Utc_Offset = tu.utc_offset

                If tu.description <> "" Then
                    Acc.Description = MyApp.ToUTF8DB(tu.description) ' Encoding.Default.GetString(Encoding.Convert(Encoding.UTF8, Encoding.Default, Encoding.UTF8.GetBytes(tu.description)))
                End If

                Acc.Url = tu.url

                Acc.Account_Add_Info.Lang = tu.lang

                Acc.Account_Add_Info.Post_Count = tu.statuses_count
                Acc.Account_Add_Info.Profile_Update = Date.UtcNow
                Acc.Account_Add_Info.Follower_Count = tu.followers_count
                Acc.Account_Add_Info.Friend_Count = tu.friends_count

                Acc.Account_Add_Info.Private_Post = tu.protected
                Acc.Account_Add_Info.Verified = tu.verified
                Acc.Account_Add_Info.List_Memberships_Count = tu.listed_count

                If tu.status IsNot Nothing Then
                    Acc.Account_Add_Info.Post_Last_Pubb_Date = tu.status.created_at
                End If

                db.SubmitChanges()

                Return Acc

            End Function

#End Region

#Region "FOLLOWER"

            'Public Sub DownloadAccountFollowers(Acc As mDB.Account)
            '    Dim tc = New WebApi.Twitter.TwitterClient(oauth)

            '    'prendo l'ulmito cursor
            '    Dim Cursor = Acc.Account_Update.Follower_Last_Code

            '    If Cursor = "" Then Cursor = "-1"

            '    Do
            '        'scarico i followers
            '        Dim Foll = tc.GetFollowers("", Acc.Account_Code, Cursor)

            '        MyApp.WriteProcLog(SF("(tab)(tab)update followers: {1}", Acc.Fullname, Foll.ids.Count), AutoProcType.UPDATE_ACCOUNTS)


            '        'db.TabAccount_Link.Where("account_id", "=", acc.Id).Delete.ExecuteCommand()

            '        For Each f In Foll.ids

            '            '-------------------------------------------------------------
            '            'crea l'account
            '            Dim FollAcc = db.TAB.Account.BY.Account.AccountCode(f).ToObj
            '            If FollAcc Is Nothing Then
            '                FollAcc = (New mDB.Account).SetDefault
            '                FollAcc.Network_Id = mDB.NetworkType.TWITTER
            '                FollAcc.Account_Code = f
            '                FollAcc.InsertOnSubmit(db)

            '                db.SubmitChanges()
            '            End If

            '            '-------------------------------------------------------------
            '            'crea/aggiona il link
            '            Dim AccLink = db.TAB.Account_Link.GetByPKs(Acc.Id, mDB.Account_Link.Type.FOLLOWER, FollAcc.Id)
            '            If AccLink Is Nothing Then
            '                AccLink = New mDB.Account_Link With {
            '                    .Account_Id = Acc.Id,
            '                    .Account_Link_Id = FollAcc.Id,
            '                    .Link_Type_Id = mDB.Account_Link.Type.FOLLOWER,
            '                    .Update_Date = Date.UtcNow,
            '                    .Create_Date = Date.UtcNow
            '                }
            '                db.TAB.Account_Link.InsertOnSubmit(AccLink)

            '            End If

            '            AccLink.Updating = 1

            '            db.SubmitChanges()


            '        Next
            '        Cursor = Foll.next_cursor_str

            '        '-------------------------------------------------------------
            '        'aggiona il link_update
            '        Acc.Account_Update.Follower_Last_Code = Cursor

            '        db.SubmitChanges()

            '    Loop Until Cursor = "0"

            '    ' se ho finito aggiorno tutto
            '    If Cursor = "0" Then
            '        ' cancello tutti i link che non sono stati aggiornati
            '        db.TAB.Account_Link.
            '            BY.Account_Link.Account_Id(Acc.Id, mDB.Account_Link.Type.FOLLOWER).
            '            Where("updating", "=", False).
            '        Delete.ExecuteCommand()

            '        'imposto gli aggiornati a 0
            '        db.TAB.Account_Link.
            '            BY.Account_Link.Account_Id(Acc.Id, mDB.Account_Link.Type.FOLLOWER).
            '        Update.UpdateValue("updating", "0").ExecuteCommand()

            '        'aggiorno il linkupdate
            '        Acc.Account_Update.Follower_Last_Code = ""
            '        Acc.Account_Update.Follower_Update_Date = Date.UtcNow
            '        Acc.Account_Update.Follower_Update_Count = Acc.Account_Update.Follower_Count

            '        db.SubmitChanges()


            '    End If



            'End Sub

            Public Function DownloadAccountFollowers(Acc As mDB.Account) As Boolean
                Dim Maxfollower = 20000
                Dim FollowerCount = 0
                Dim tc = New WebApi.Twitter.TwitterClient(oauth)

                'prendo l'ulmito cursor
                Dim Cursor = Acc.Account_Update.Follower_Last_Code

                If Cursor = "" Or Cursor = "0" Then Cursor = "-1"

                '---------------------------------------------
                'scarico i followers
                '---------------------------------------------
                Do
                    Dim Foll = tc.GetFollowers("", Acc.Account_Code, Cursor)

                    MyApp.WriteProcLog(SF("(tab)(tab)update followers: {1}", Acc.Fullname, Foll.ids.Count), Task.TaskType.UPDATE_ACCOUNTS)

                    For Each f In Foll.ids

                        If Acc.Id = MyApp.AccountDebug Then
                            MyApp.WriteProcLog(SF("(tab)(tab)update followers id: {1}", Acc.Fullname, f), Task.TaskType.DEBUG)
                        End If

                        Acc.AddAccountLink(mDB._Account_Link.Type.FOLLOWER, f, AccType.TWITTER_ACCOUNT)

                    Next
                    Cursor = Foll.next_cursor_str

                    'aggiona il link_update
                    Acc.Account_Update.Follower_Last_Code = Cursor

                    db.SubmitChanges()

                    FollowerCount += Foll.ids.Count

                Loop Until Cursor = "0" 'Or FollowerCount > Maxfollower


                Return Cursor = "0"

                ''---------------------------------------------
                '' se ho finito aggiorno tutto
                ''---------------------------------------------
                'If Cursor = "0" Then

                '    '---------------------------------------------
                '    ' DEBUG
                '    '---------------------------------------------
                '    If Acc.Id = MyApp.AccountDebug Then
                '        Dim acclinkold = Acc.Tab_Account_Link(GloukDB.Account_Link.Type.FOLLOWER).
                '            REL.Account_Link.Account.
                '            Where("updating", "=", False).SetSelect("account.account_code").
                '        ToList(Of String)("account_code")

                '        For Each acccode In acclinkold
                '            MyApp.WriteProcLog(SF("(tab)(tab)update followers become old: {0} ", acccode), Task.TaskType.DEBUG)
                '        Next

                '    End If

                '    '---------------------------------------------
                '    ' i follower che non si sono aggionati li faccio diventare old follower
                '    Dim qUpdateFoll = db.TAB.Account_Link.
                '        BY.Account_Link.Account_Id(Acc.Id, mDB.Account_Link.Type.FOLLOWER).
                '        Where("updating", "=", False).
                '        Update.
                '        UpdateValue("link_type_id", mDB.Account_Link.Type.FOLLOWER_OLD).
                '        UpdateValue("create_date", Date.UtcNow)

                '    'se attivata l'analisi e non ci sono limiti
                '    If Acc.Account_Auth.Analysis_Followers And Acc.Account_Auth.Analysis_Followers_Limit = 0 Then
                '        qUpdateFoll.UpdateValue("analysis", False)
                '    End If

                '    qUpdateFoll.ExecuteCommand()

                '    Dim res1 = qUpdateFoll.ExecuteCommand()

                '    '---------------------------------------------
                '    'reimposto updating a 0 per i follower
                '    Dim res2 = db.TAB.Account_Link.
                '        BY.Account_Link.Account_Id(Acc.Id, mDB.Account_Link.Type.FOLLOWER).
                '        Update.
                '        UpdateValue("updating", 0).
                '    ExecuteCommand()

                '    '---------------------------------------------
                '    ' DEBUG
                '    '---------------------------------------------
                '    If Acc.Id = MyApp.AccountDebug Then
                '        MyApp.WriteProcLog(SF("(tab)(tab)update followers update data: become old: {0} - set foll 0: {1}", res1, res2), Task.TaskType.DEBUG)
                '    End If

                '    '---------------------------------------------
                '    'aggiorno i follower per l'analisi
                '    If Acc.Account_Auth.Analysis_Followers Then

                '        Acc.Tab_Account_Link.
                '            Where("link_type_id", "<>", mDB.Account_Link.Type.FOLLOWER).
                '            Update.
                '            UpdateValue("analysis", False).
                '        ExecuteCommand()

                '        If Acc.Account_Auth.Analysis_Followers_Limit = 0 Then

                '            Acc.Tab_Account_Link.
                '                Where("link_type_id", "=", mDB.Account_Link.Type.FOLLOWER).
                '                Update.
                '                UpdateValue("analysis", True).
                '            ExecuteCommand()

                '        Else

                '            Dim tot = Acc.Tab_Account_Link(True).SetSelect("count(*)").ToObj(Of Integer)()

                '            Dim q = db.TAB.Account_Link.
                '                BY.Account_Link.Account_Id(Acc.Id, mDB.Account_Link.Type.FOLLOWER).
                '                Limit(Math.Abs(Acc.Account_Auth.Analysis_Followers_Limit - tot))

                '            Dim analysis = Acc.Account_Auth.Analysis_Followers_Limit - tot > 0

                '            db.TAB.Account_Link.
                '                Join(q, "account_link_id", "account_link.account_link_id", "AccAnalysis", "").
                '                Update.
                '                UpdateValue("analysis", analysis).
                '            ExecuteCommand()

                '        End If
                '    End If




                '    'aggiorno il linkupdate
                '    Acc.Account_Update.Follower_Last_Code = ""
                '    Acc.Account_Update.Follower_Update = Date.UtcNow
                '    Acc.Account_Update.Follower_Update_Count = Acc.Account_Update.Follower_Count

                '    db.SubmitChanges()

                'End If


            End Function

            Public Function DownloadAccountFriends(Acc As mDB.Account) As Boolean
                Dim tc = New WebApi.Twitter.TwitterClient(oauth)

                'prendo l'ulmito cursor
                Dim Cursor = Acc.Account_Update.Friend_Last_Code

                If Cursor = "" Then Cursor = "-1"

                Do
                    'scarico i friends
                    Dim Foll = tc.GetFriends("", Acc.Account_Code, Cursor)

                    MyApp.WriteProcLog(SF("(tab)(tab)update Friends: {1}", Acc.Fullname, Foll.ids.Count), Task.TaskType.UPDATE_ACCOUNTS)

                    For Each f In Foll.ids

                        Acc.AddAccountLink(mDB._Account_Link.Type.FRIENDS, f, AccType.TWITTER_ACCOUNT)

                    Next
                    Cursor = Foll.next_cursor_str

                    '-------------------------------------------------------------
                    'aggiona il link_update
                    Acc.Account_Update.Friend_Last_Code = Cursor

                    db.SubmitChanges()

                Loop Until Cursor = "0"

                Return Cursor = "0"

                '' se ho finito aggiorno tutto
                'If Cursor = "0" Then
                '    ' mofifico in olf followre
                '    db.TAB.Account_Link.
                '        BY.Account_Link.Account_Id(Acc.Id, mDB.Account_Link.Type.FRIENDS).
                '        Where("updating", "=", False).
                '        Update.
                '        UpdateValue("link_type_id", mDB.Account_Link.Type.FRIEND_OLD).
                '        UpdateValue("create_date", Date.UtcNow).
                '    ExecuteCommand()

                '    'imposto gli aggiornati a 0
                '    db.TAB.Account_Link.
                '        BY.Account_Link.Account_Id(Acc.Id, mDB.Account_Link.Type.FRIENDS).
                '        Update.
                '        UpdateValue("updating", 0).
                '    ExecuteCommand()

                '    'aggiorno il linkupdate
                '    Acc.Account_Update.Friend_Last_Code = ""
                '    Acc.Account_Update.Friend_Update = Date.UtcNow
                '    Acc.Account_Update.Friend_Update_Count = Acc.Account_Update.Friend_Count

                '    db.SubmitChanges()

                'End If


            End Function


#End Region

#Region "LIST"

            Public Function DownloadAccountLists(Acc As mDB.Account) As Boolean
                Dim Maxfollower = 20000
                Dim FollowerCount = 0
                Dim tc = New WebApi.Twitter.TwitterClient(oauth)

                'prendo l'ulmito cursor
                Dim Cursor = ""

                If Cursor = "" Or Cursor = "0" Then Cursor = "-1"

                '---------------------------------------------
                'scarico le liste
                '---------------------------------------------
                Do
                    Dim Foll = tc.GetListsOwnerships("", Acc.Account_Code, Cursor)

                    MyApp.WriteProcLog(SF("(tab)update list: {0}, count: {1}", Acc.ToString, Foll.lists.Count), Task.TaskType.UPDATE_ACCOUNTS)

                    For Each l In Foll.lists

                        Dim List = Me.UpdateList(Acc, l)

                        DownloadAccountListUsers(List)

                    Next
                    Cursor = Foll.next_cursor_str

                    db.SubmitChanges()


                Loop Until Cursor = "0"

                'cancello le liste non aggiornate
                Acc.Tab_List.Where("updating", "=", False, "list_type_id", "<>", mDB.List.Type.LOCAL).Delete.ExecuteCommand()
                'rimetto gli aggiornamenti a 0
                Acc.Tab_List.Update.UpdateValue("updating", 0).ExecuteCommand()

                Return Cursor = "0"

            End Function

            Public Function DownloadAccountListUsers(List As mDB.List) As Boolean
                Dim tc = New WebApi.Twitter.TwitterClient(oauth)

                'prendo l'ulmito cursor
                Dim Cursor = ""

                If Cursor = "" Or Cursor = "0" Then Cursor = "-1"

                '---------------------------------------------
                'scarico gli account della lista
                '---------------------------------------------
                List.Tab_List_Account.Delete.ExecuteCommand()

                Do
                    Dim Foll = tc.GetListsMembers(List.List_Code, Cursor)

                    MyApp.WriteProcLog(SF("(tab)(tab)update list user: '{0}', user count: ({1})", List.Fullname, Foll.users.Count), Task.TaskType.UPDATE_ACCOUNTS)


                    Me.UpdateListUsers(List, Foll.users.Select(Function(o) o.id_str).ToList)

                    Cursor = Foll.next_cursor_str

                Loop Until Cursor = "0" 'Or FollowerCount > Maxfollower

                Return Cursor = "0"

            End Function


            Public Function UpdateList(Acc As mDB.Account, l As WebApi.Twitter.List) As mDB.List

                'aggiorna favorito
                Dim list = db.TAB.List.BY.List.List_Code(l.id_str).ToObj

                If list Is Nothing Then
                    list = New mDB.List With {.List_Code = l.id_str, .Account_Id = Acc.Id}
                    db.TAB.List.InsertOnSubmit(list)
                End If

                list.Account_Count = l.member_count
                list.Create_Date = l.created_at
                list.Description = l.description
                list.Fullname = l.name
                list.List_Type_Id = IIf(l.mode = "private", mDB.List.Type.PRIVATE, mDB.List.Type.PUBLIC)
                list.Updating = True
                list.List_Update = Date.UtcNow

                db.SubmitChanges()

                Return list

            End Function

            Public Function UpdateListUsers(l As mDB.List, AccCodes As List(Of String)) As Boolean

                db.InitMultiRowsInsert()

                For Each AccCode In AccCodes
                    Dim Acc = mDB.Account.GetForUpdate(AccCode, AccType.TWITTER_ACCOUNT)

                    Dim Acclist = New mDB.List_Account With {.List_Id = l.Id, .Account_Id = Acc.Id}
                    db.InsertRowOnSubmit(Acclist)


                Next
                db.SubmitChanges()


                Return True

            End Function


            Public Function AddList(l As mDB.List, accs As List(Of String)) As mDB.List

                Dim tc = New WebApi.Twitter.TwitterClient(oauth)

                Dim listt = tc.PostListsCreate(l.Fullname, "", "")

                l.List_Code = listt.id_str

                db.TAB.List.InsertOnSubmit(l)
                db.SubmitChanges()

                tc.PostListsMembersCreateAll(l.List_Code, String.Join(",", accs))


                Return l

            End Function

            Public Function REmoveList()

            End Function

#End Region


#Region "POST DOWNLOAD"

            Public Sub DownloadAccountPostsAsync(param As Object)

                Try

                    HttpContext.Current = Me.HttpContextCurrent
                    Me.db = mDB.GetDB '(False)

                    Dim Id As Integer = param.id
                    Dim Mode As mDB.Account.UpdatePostMode = param.mode

                    Dim Acc = db.TAB.Account.GetByPK(Id)


                    Dim EndDownload = False
                    Do


                        Dim UserAcc = mDB.Account_Auth.GetUserAccountAvailable(mDB.Account_Auth.ServiceType.POST, AccType.TWITTER_ACCOUNT)


                        Try

                            'db.ExecuteCommand("bbbbb")


                            If UserAcc IsNot Nothing Then
                                Me.oauth = UserAcc.getOauth

                                Me.DownloadAccountPosts(Acc, Mode)

                            Else

                                MyApp.WriteProcLog(SF("(tab)(tab)error update follower post: user account not Available"), Task.TaskType.UPDATE_POSTS)
                                Throw New WebApi.Net.ExceptionTooManyRequestsAllAccount

                            End If

                            EndDownload = True

                        Catch ex As WebApi.Net.ExceptionAPITooManyRequests

                            MyApp.WriteProcLog(SF("(tab)(tab)error update follower post: ExceptionAPITooManyRequests: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), Task.TaskType.UPDATE_POSTS)
                            UserAcc.SetLastRateLimit(mDB.Account_Auth.ServiceType.POST)

                        Catch ex As WebApi.Net.ExceptionAPIAccount

                            MyApp.WriteProcLog(SF("(tab)(tab)error update follower post: ExceptionAPIAccount: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), Task.TaskType.UPDATE_POSTS)
                            UserAcc.SetLastRateLimit(mDB.Account_Auth.ServiceType.POST)

                            'Catch ex As Exception

                            '    HttpContext.Current.Items("Exception_UpdateUserPosts") = ex
                            '    EndDownload = True

                        End Try

                    Loop Until EndDownload

                Catch ex As Exception

                    HttpContext.Current.Items("Exception_UpdateUserPosts") = ex
                    'EndDownload = True


                End Try


            End Sub
            'Public Sub DownloadAccountPosts_old(Acc As mDB.Account)

            '    Const NumPostFindEnd = 100
            '    'creo il client con i dati dell'account collegato
            '    Dim tc = New WebApi.Twitter.TwitterClient(Me.oauth)


            '    Dim EndDownload = False
            '    Dim Last_Code = ""


            '    MyApp.WriteAppLog(SF("(tab)(tab)begin update post: {0}", Acc.Username))

            '    '---------------------------------------------------------------------------
            '    ' verifica i vecchi post

            '    If Acc.Account_Update.Post_Check_Old Then



            '        Do Until EndDownload

            '            Last_Code = ""
            '            Dim OldPost = db.TAB.AccountPost.BY.AccountPost.Account_Id(Acc.Id).OrderBy("pubb_date asc").Limit(1).ToObj

            '            'prendo il post + nuovo
            '            If OldPost IsNot Nothing Then
            '                Last_Code = OldPost.Post_Code
            '            End If

            '            Dim tweets As List(Of WebApi.Twitter.Tweet)

            '            Try
            '                tweets = tc.GetTweets("", Acc.Account_Code, "", Last_Code)

            '            Catch ex As WebApi.Net.ExceptionRequest

            '                MyApp.WriteAppLog(SF("(tab)(tab)(tab)ExceptionAccessUnauthorized old post: {0}, {1}", tc.LastError.code, tc.LastError.message))
            '                Exit Do

            '            End Try


            '            MyApp.WriteAppLog(SF("(tab)(tab)(tab)old post: {0}, {1}", tweets.Count, Acc.Username))

            '            For Each t In tweets

            '                UpdateAccountPost(Acc, t)

            '            Next

            '            EndDownload = tweets.Count <= NumPostFindEnd

            '        Loop

            '        If EndDownload Then
            '            Acc.Account_Update.Post_Check_Old = db.ToBool(False)
            '            db.SubmitChanges()
            '        End If


            '    End If


            '    '---------------------------------------------------------------------------
            '    ' verifica i nuovi post


            '    Dim First_Code = ""
            '    Dim LastPost = db.TAB.AccountPost.BY.AccountPost.Account_Id(Acc.Id).OrderBy("pubb_date desc").Limit(1).ToObj

            '    'prendo il post + nuovo
            '    If LastPost IsNot Nothing Then
            '        First_Code = LastPost.Post_Code
            '    End If
            '    Last_Code = ""

            '    EndDownload = False
            '    Do Until EndDownload


            '        Dim tweets As List(Of WebApi.Twitter.Tweet)

            '        Try
            '            tweets = tc.GetTweets("", Acc.Account_Code, First_Code, Last_Code)

            '        Catch ex As WebApi.Net.ExceptionRequest

            '            MyApp.WriteAppLog(SF("(tab)(tab)(tab)ExceptionRequest new post: {0}, {1}", tc.LastError.code, tc.LastError.message))
            '            Exit Do

            '        End Try


            '        MyApp.WriteAppLog(SF("(tab)(tab)(tab)new post: {0}, {1}", tweets.Count, Acc.Username))

            '        For Each t In tweets
            '            UpdateAccountPost(Acc, t)
            '        Next

            '        If tweets.Count > 0 Then
            '            Last_Code = tweets.Last.id_str
            '        End If

            '        EndDownload = tweets.Count <= NumPostFindEnd

            '    Loop

            '    If EndDownload Then
            '        Acc.Account_Update.Post_Update_Count = Acc.Account_Update.Post_Count
            '        Acc.Account_Update.Post_Update = Date.UtcNow
            '        db.SubmitChanges()
            '    End If

            '    MyApp.WriteAppLog(SF("(tab)(tab)end update post: {0}", Acc.Username))

            'End Sub
            'Public Function GetLastPostCod(Acc As mDB.Account) As String


            '    'Dim LastPost = db.TAB.AccountPost.BY.AccountPost.Account_Id(Acc.Id).OrderBy("pubb_date desc").Limit(1).ToObj
            '    Dim LastPost = Acc._Tab_Account_Post.OrderBy("pubb_date desc").Limit(1).ToObj
            '    'prendo il post + nuovo
            '    If LastPost IsNot Nothing Then
            '        Return LastPost.Post_Code
            '    Else
            '        Return ""
            '    End If

            'End Function
            Public Sub DownloadAccountPosts(Acc As mDB.Account, Mode As mDB.Account.UpdatePostMode)

                Dim NumPostFindEnd = 100
                Dim NumPostToDownload = 500
                If Mode = mDB.Account.UpdatePostMode.PROFILE Then
                    NumPostToDownload = 4000
                End If

                'creo il client con i dati dell'account collegato
                Dim tc = New WebApi.Twitter.TwitterClient(Me.oauth)

                Dim ContinuePrevDownload = False
                Dim Since_id = ""
                Dim Max_id = ""

                Dim IsUserAccount = Acc.Tab_User_Account.ToList.Count > 0

                Dim PostCount = 0

                Dim Codes = Acc.Account_Add_Info.Post_Last_Code.ToString.Split(",")

                If Codes.Length > 1 Then
                    ContinuePrevDownload = True
                    Since_id = Codes(0)
                    Max_id = Codes(1)
                Else
                    Since_id = Acc.GetLastPostCode   ' Me.GetLastPostCod(Acc)
                End If

                MyApp.WriteProcLog(SF("(tab)(tab)TWITTER begin update post: {0}", Acc.Username), Task.TaskType.UPDATE_POSTS)

                Dim EndDownload = False
                Dim PostUpdateCount = Acc.Account_Add_Info.Post_Count
                Dim PostUpdateDate = Date.UtcNow

                Do Until EndDownload

                    Dim tweets As List(Of WebApi.Twitter.Tweet)

                    Try

                        tweets = tc.GetTweets("", Acc.Account_Code, Since_id, Max_id)

                    Catch ex As WebApi.Net.ExceptionAPIResponse

                        MyApp.WriteProcLog(SF("(tab)(tab)(tab)ExceptionRequest post: {0}, {1}", tc.LastError.Code, tc.LastError.Message), Task.TaskType.UPDATE_POSTS)

                        'IMPORTANTE se non si ahnno gli accessi per scaricare i post esce subito e mette com update dei post a -1
                        If tc.LastError.Code = 401 Or tc.LastError.Code = 34 Then
                            EndDownload = True
                            PostUpdateCount = -1
                            'IMPORTANTE se non scarica metto la data avanti di un mese per provare a riscaricare
                            PostUpdateDate = PostUpdateDate.AddMonths(1)
                        End If

                        Exit Do

                    End Try

                    MyApp.WriteProcLog(SF("(tab)(tab)(tab)post: {0}, {1}", tweets.Count, Acc.Username), Task.TaskType.UPDATE_POSTS)

                    PostCount += tweets.Count

                    Dim IsNewPost As Boolean
                    Dim DateActPost As New List(Of Date)
                    For Each t In tweets
                        Me.UpdateAccountPost(Acc, t, IsUserAccount, IsNewPost)
                        If IsNewPost Then
                            DateActPost.Add(t.created_at)
                        End If
                    Next
                    Acc.SetActivity(DateActPost)

                    If tweets.Count > 0 Then
                        Max_id = tweets.Last.id_str
                    End If

                    Acc.Account_Add_Info.Post_Last_Code = SF("{0},{1}", Since_id, Max_id)
                    db.SubmitChanges()


                    If tweets.Count <= NumPostFindEnd Or PostCount > NumPostToDownload Then
                        EndDownload = True
                    End If

                    If EndDownload And ContinuePrevDownload Then
                        ContinuePrevDownload = False
                        EndDownload = False
                        Since_id = Acc.GetLastPostCode  ' Me.GetLastPostCod(Acc)
                        Max_id = ""
                        PostCount = 0
                    End If

                Loop

                If EndDownload Then
                    Acc.Account_Add_Info.Post_Update_Count = PostUpdateCount
                    Acc.Account_Add_Info.Post_Update = PostUpdateDate
                    Acc.Account_Add_Info.Post_Last_Code = ""
                    db.SubmitChanges()
                End If

                MyApp.WriteProcLog(SF("(tab)(tab)end update post: {0}", Acc.Username), Task.TaskType.UPDATE_POSTS)

            End Sub

            Public Function UpdateAccountPost(Acc As mDB.Account, t As WebApi.Twitter.Tweet, SaveEntities As Boolean) As mDB._Account_Post

                Return UpdateAccountPost(Acc, t, SaveEntities)

            End Function


            Public Function UpdateAccountPost(Acc As mDB.Account, t As WebApi.Twitter.Tweet, SaveEntities As Boolean, ByRef IsNewPost As Boolean) As mDB._Account_Post

                IsNewPost = False
                'aggiorna post
                Dim Post = Acc._Tab_Account_Post.BY._Account_Post._Post_Code(t.id_str).ToObj

                If Post Is Nothing Then
                    IsNewPost = True
                    Post = New mDB._Account_Post
                    db.InsertOnSubmit(Acc.ArchivePost.Table_Name, Post)
                End If

                Post.Post_Code = t.id_str
                Post.Post_Text = MyApp.ToUTF8DB(t.text) 'Encoding.Default.GetString(Encoding.Convert(Encoding.UTF8, Encoding.Default, Encoding.UTF8.GetBytes(t.text)))
                Post.Pubb_Date = t.created_at
                Post.Account_Id = Acc.Id

                db.SubmitChanges()


                '-------------------------------------------------------
                ' messaggi
                ' IMPORTANTE se un post è una risposta ad un altro messaggio mette il post anche tra i messaggi
                If SaveEntities Then
                    If t.in_reply_to_status_id_str <> "" Then
                        'Me.UpdateMessagePost(New mDB.Account With {.Id = 0}, t)
                        Me.UpdateMessagePost(Acc, t)
                    End If

                    If t.retweeted_status IsNot Nothing Then
                        Dim share = Me.UpdateSharePost(Acc, t.retweeted_status)
                        Me.UpdateSharePostDetail(share, t)

                    End If

                End If

                '-------------------------------------------------------
                ' salva attributi
                SaveEntities = False

                If SaveEntities Then
                    If t.entities IsNot Nothing Then
                        If t.entities.urls IsNot Nothing AndAlso t.entities.urls.Count > 0 Then

                            For Each u In t.entities.urls

                                Dim Link = db.TAB.Link.BY.Link.Short_Url(u.url).ToObj

                                If Link Is Nothing Then
                                    Link = New mDB.Link With {
                                        .Short_Url = u.url, .Expanded_Url = u.expanded_url
                                    }
                                    db.TAB.Link.InsertOnSubmit(Link)
                                    db.SubmitChanges()
                                End If

                                Dim LinkPost = New mDB.Link_Post With {
                                    .Link_Id = Link.Id, .Post_Id = Post.Id
                                }
                                db.TAB.Link_Post.InsertOnSubmit(LinkPost)
                            Next

                            db.SubmitChanges()

                        End If
                    End If
                End If



                Return Post

            End Function

#End Region

#Region "MESSAGE"


            Public Sub DownloadConversationMessage(Mess As mDB.Message_Post)


                Dim acc = New mDB.Account With {.Id = 0}

                Dim EndDownload = False
                Do

                    Dim UserAcc = mDB.Account_Auth.GetUserAccountAvailable(mDB.Account_Auth.ServiceType.SHARE_POST, AccType.TWITTER_ACCOUNT)

                    Try

                        If UserAcc IsNot Nothing Then
                            Me.oauth = UserAcc.getOauth
                        Else
                            Throw New WebApi.Net.ExceptionTooManyRequestsAllAccount
                        End If

                        'aggiorna messaggio
                        Dim ReplyMess = db.TAB.Message_Post.BY.Message_Post.Post_Code(Mess.Reply_To_Post_Code).ToObj

                        If ReplyMess Is Nothing Then
                            MyApp.WriteProcLog(SF("(tab)(tab)donwload conv: {0}", Mess.Reply_To_Post_Code), Task.TaskType.UPDATE_ACCOUNTS)

                            Dim tc = New WebApi.Twitter.TwitterClient(Me.oauth)
                            Dim t = tc.GetTweet(Mess.Reply_To_Post_Code)


                            Dim Conv = UpdateMessagePost(acc, t)
                        Else
                            MyApp.WriteProcLog(SF("(tab)(tab)exits conv: {0}", Mess.Reply_To_Post_Code), Task.TaskType.UPDATE_ACCOUNTS)

                        End If


                        EndDownload = True

                    Catch ex As WebApi.Net.ExceptionAPIResponse

                        '404:"message":"Sorry, that page does not exist","code":34
                        EndDownload = True

                    Catch ex As WebApi.Net.ExceptionAPITooManyRequests

                        MyApp.WriteProcLog(SF("(tab)(tab)error update message conv: ExceptionAPITooManyRequests: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), Task.TaskType.UPDATE_ACCOUNTS)
                        UserAcc.SetLastRateLimit(mDB.Account_Auth.ServiceType.SHARE_POST)

                    Catch ex As WebApi.Net.ExceptionAPIAccount

                        MyApp.WriteProcLog(SF("(tab)(tab)error update message conv: ExceptionAPIAccount: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), Task.TaskType.UPDATE_ACCOUNTS)
                        UserAcc.SetLastRateLimit(mDB.Account_Auth.ServiceType.SHARE_POST)

                    End Try

                Loop Until EndDownload

                If EndDownload Then
                    'Mess.Parent_Post_Update = True
                    Mess.Parent_Post_Update = False
                    db.SubmitChanges()

                End If


            End Sub

            'Public Function GetLastMessCod(Acc As mDB.Account) As String


            '    Dim LastMess = db.TAB.Message_Post.BY.Message_Post.To_Account_Id(Acc.Id).OrderBy("pubb_date desc").Limit(1).ToObj
            '    'prendo il messaggio + nuovo
            '    If LastMess IsNot Nothing Then
            '        Return LastMess.Post_Code
            '    Else
            '        Return ""
            '    End If

            'End Function
            Public Sub DownloadAccountMessagePosts(Acc As mDB.Account)

                Const NumMessFindEnd = 100
                'creo il client con i dati dell'account collegato
                Dim tc = New WebApi.Twitter.TwitterClient(Me.oauth)

                Dim EndDownload = False
                Dim ContinuePrevDownload = False
                Dim Since_id = ""
                Dim Max_id = ""

                Dim Codes = Acc.Account_Update.Message_Post_Last_Code.ToString.Split(",")

                If Codes.Length > 1 Then
                    ContinuePrevDownload = True
                    Since_id = Codes(0)
                    Max_id = Codes(1)
                Else
                    Since_id = Acc.GetLastMessagePostCode ' Me.GetLastMessCod(Acc)
                End If

                MyApp.WriteProcLog(SF("(tab)(tab)TWITTER begin update message post: {0} ({1})", Acc.Fullname, Acc.Username), Task.TaskType.UPDATE_ACCOUNTS)

                EndDownload = False
                Do Until EndDownload

                    Dim tweets As List(Of WebApi.Twitter.Tweet)

                    'Try

                    tweets = tc.GetMentions(Since_id, Max_id)

                    'Catch ex As WebApi.Net.ExceptionAPIResponse

                    '    'MyApp.WriteProcLog(SF("(tab)(tab)(tab)ExceptionRequest message: {0}, {1}", tc.LastError.Code, tc.LastError.Message), AutoProcType.UPDATE_ACCOUNTS)
                    '    Exit Do

                    'End Try

                    MyApp.WriteProcLog(SF("(tab)(tab)(tab)message post: {0}, {1}", tweets.Count, Acc.Username), Task.TaskType.UPDATE_ACCOUNTS)

                    For Each t In tweets
                        UpdateMessagePost(Acc, t)
                    Next

                    If tweets.Count > 0 Then
                        Max_id = tweets.Last.id_str
                    End If

                    Acc.Account_Update.Message_Post_Last_Code = SF("{0},{1}", Since_id, Max_id)
                    db.SubmitChanges()

                    EndDownload = tweets.Count <= NumMessFindEnd

                    If EndDownload And ContinuePrevDownload Then
                        ContinuePrevDownload = False
                        EndDownload = False
                        Since_id = Acc.GetLastMessagePostCode ' Me.GetLastMessCod(Acc)
                        Max_id = ""
                    End If

                Loop

                If EndDownload Then
                    Acc.Account_Update.Message_Post_Update = Date.UtcNow
                    Acc.Account_Update.Message_Post_Last_Code = ""
                    'IMPORTANTE se vengono scaricati dei messaggi rimette a 0 la data di aggiornamento dei profili connessi in modo che i trend vengano creati solo quando tutti gli accorunt sono stati scaricati
                    'Acc.Account_Update.Profile_Related_Update = Date.MinValue
                    db.SubmitChanges()
                End If

                MyApp.WriteProcLog(SF("(tab)(tab)end update message post: {0} ({1})", Acc.Fullname, Acc.Username), Task.TaskType.UPDATE_ACCOUNTS)

            End Sub


            'Public Sub DownloadAccountPrivatePosts(Acc As mDB.Account)

            '    Const NumMessFindEnd = 100
            '    'creo il client con i dati dell'account collegato
            '    Dim tc = New WebApi.Twitter.TwitterClient(Me.oauth)

            '    Dim EndDownload = False
            '    Dim ContinuePrevDownload = False
            '    Dim Since_id = ""
            '    Dim Max_id = ""

            '    Dim Codes = Acc.Account_Update.Private_Post_Last_Code.ToString.Split(",")

            '    If Codes.Length > 1 Then
            '        ContinuePrevDownload = True
            '        Since_id = Codes(0)
            '        Max_id = Codes(1)
            '    Else
            '        Since_id = Acc.GetLastPrivatePostCode  ' Me.GetLastMessCod(Acc)
            '    End If

            '    MyApp.WriteProcLog(SF("(tab)(tab)TWITTER begin update private post: {0} ({1})", Acc.Fullname, Acc.Username), AutoProcType.UPDATE_ACCOUNTS)

            '    EndDownload = False
            '    Do Until EndDownload

            '        Dim tweets As List(Of WebApi.Twitter.Tweet)

            '        Try

            '            tweets = tc.GetDirectMessage(Since_id, Max_id)
            '            tweets.AddRange(tc.GetDirectMessageSent(Since_id, Max_id))

            '        Catch ex As WebApi.Net.ExceptionRequest

            '            Exit Do

            '        End Try

            '        MyApp.WriteProcLog(SF("(tab)(tab)(tab)private post: {0}, {1}", tweets.Count, Acc.Username), AutoProcType.UPDATE_ACCOUNTS)

            '        tweets = tweets.OrderBy(Function(o) o.created_at).ToList
            '        For Each t In tweets
            '            UpdatePrivatePost(Acc, t)
            '        Next

            '        If tweets.Count > 0 Then
            '            Max_id = tweets.Last.id_str
            '        End If

            '        Acc.Account_Update.Private_Post_Last_Code = SF("{0},{1}", Since_id, Max_id)
            '        db.SubmitChanges()

            '        EndDownload = tweets.Count <= NumMessFindEnd

            '        If EndDownload And ContinuePrevDownload Then
            '            ContinuePrevDownload = False
            '            EndDownload = False
            '            Since_id = Acc.GetLastPrivatePostCode ' Me.GetLastMessCod(Acc)
            '            Max_id = ""
            '        End If

            '    Loop

            '    If EndDownload Then
            '        Acc.Account_Update.Private_Post_Update = Date.UtcNow
            '        Acc.Account_Update.Private_Post_Last_Code = ""
            '        'IMPORTANTE se vengono scaricati dei messaggi rimette a 0 la data di aggiornamento dei profili connessi in modo che i trend vengano creati solo quando tutti gli accorunt sono stati scaricati
            '        'Acc.Account_Update.Profile_Related_Update = Date.MinValue
            '        db.SubmitChanges()
            '    End If

            '    MyApp.WriteProcLog(SF("(tab)(tab)end update private post: {0} ({1})", Acc.Fullname, Acc.Username), AutoProcType.UPDATE_ACCOUNTS)

            'End Sub

            Public Sub DownloadAccountPrivatePosts(Acc As mDB.Account)

                Const NumMessFindEnd = 100
                'creo il client con i dati dell'account collegato
                Dim tc = New WebApi.Twitter.TwitterClient(Me.oauth)

                Dim EndDownload = False
                Dim Since_id = ""
                Dim Max_id = ""

                Since_id = Acc.GetLastPrivatePostCode(False)  ' Me.GetLastMessCod(Acc)

                MyApp.WriteProcLog(SF("(tab)(tab)TWITTER begin update private post: {0} ({1})", Acc.Fullname, Acc.Username), Task.TaskType.UPDATE_ACCOUNTS)

                EndDownload = False
                Do Until EndDownload

                    Dim tweets As List(Of WebApi.Twitter.Tweet)

                    tweets = tc.GetDirectMessage(Since_id, Max_id)
                    MyApp.WriteProcLog(SF("(tab)(tab)(tab)private post recivend: {0}, {1}", tweets.Count, Acc.Username), Task.TaskType.UPDATE_ACCOUNTS)

                    For Each t In tweets
                        UpdatePrivatePost(Acc, t)
                    Next

                    If tweets.Count > 0 Then
                        Max_id = tweets.Last.id_str
                    End If

                    EndDownload = tweets.Count <= NumMessFindEnd
                Loop

                If EndDownload Then
                    EndDownload = False

                    Max_id = ""
                    Since_id = Acc.GetLastPrivatePostCode(True)  ' Me.GetLastMessCod(Acc)

                    Do Until EndDownload

                        Dim tweets As List(Of WebApi.Twitter.Tweet)
                        tweets = tc.GetDirectMessageSent(Since_id, Max_id)

                        MyApp.WriteProcLog(SF("(tab)(tab)(tab)private post sent: {0}, {1}", tweets.Count, Acc.Username), Task.TaskType.UPDATE_ACCOUNTS)

                        For Each t In tweets
                            UpdatePrivatePost(Acc, t)
                        Next

                        If tweets.Count > 0 Then
                            Max_id = tweets.Last.id_str
                        End If

                        EndDownload = tweets.Count <= NumMessFindEnd
                    Loop

                End If

                If EndDownload Then
                    Acc.Account_Update.Private_Post_Update = Date.UtcNow
                    db.SubmitChanges()
                End If


                MyApp.WriteProcLog(SF("(tab)(tab)end update private post: {0} ({1})", Acc.Fullname, Acc.Username), Task.TaskType.UPDATE_ACCOUNTS)

            End Sub

            'Public Sub DownloadAccountMessages_old(Acc As mDB.Account)

            '    Const NumMessFindEnd = 100
            '    'creo il client con i dati dell'account collegato
            '    Dim tc = New WebApi.Twitter.TwitterClient(Me.oauth)


            '    Dim EndDownload = False
            '    Dim Last_Code = ""


            '    MyApp.WriteAppLog(SF("(tab)(tab)begin update message: {0}", Acc.Username))

            '    '---------------------------------------------------------------------------
            '    ' verifica i vecchi messaggi

            '    If Acc.Account_Update.Message_Check_Old Then

            '        Do Until EndDownload

            '            Last_Code = ""
            '            Dim OldMess = db.TAB.Message_Post.BY.Message_Post.ToAccountId(Acc.Id).OrderBy("pubb_date asc").Limit(1).ToObj

            '            'prendo il messaggio + nuovo
            '            If OldMess IsNot Nothing Then
            '                Last_Code = OldMess.Post_Code
            '            End If

            '            Dim tweets As List(Of WebApi.Twitter.Tweet)

            '            Try
            '                tweets = tc.GetMentions("", Last_Code)

            '            Catch ex As WebApi.Net.ExceptionRequest

            '                MyApp.WriteAppLog(SF("(tab)(tab)(tab)ExceptionAccessUnauthorized old message: {0}, {1}", tc.LastError.code, tc.LastError.message))
            '                Exit Do

            '            End Try

            '            MyApp.WriteAppLog(SF("(tab)(tab)(tab)old message: {0}, {1}", tweets.Count, Acc.Username))

            '            For Each t In tweets
            '                UpdateMessagePost(Acc, t)
            '            Next

            '            EndDownload = tweets.Count <= NumMessFindEnd

            '        Loop

            '        If EndDownload Then
            '            Acc.Account_Update.Message_Check_Old = db.ToBool(False)
            '            db.SubmitChanges()
            '        End If


            '    End If


            '    '---------------------------------------------------------------------------
            '    ' verifica i nuovi messaggi

            '    Dim First_Code = ""
            '    Dim LastMess = db.TAB.Message_Post.BY.Message_Post.ToAccountId(Acc.Id).OrderBy("pubb_date desc").Limit(1).ToObj

            '    'prendo il messaggio + nuovo
            '    If LastMess IsNot Nothing Then
            '        First_Code = LastMess.Post_Code
            '    End If
            '    Last_Code = ""

            '    EndDownload = False
            '    Do Until EndDownload

            '        Dim tweets As List(Of WebApi.Twitter.Tweet)

            '        Try
            '            tweets = tc.GetMentions(First_Code, Last_Code)

            '        Catch ex As WebApi.Net.ExceptionRequest

            '            MyApp.WriteAppLog(SF("(tab)(tab)(tab)ExceptionRequest new message: {0}, {1}", tc.LastError.code, tc.LastError.message))
            '            Exit Do

            '        End Try

            '        MyApp.WriteAppLog(SF("(tab)(tab)(tab)new message: {0}, {1}", tweets.Count, Acc.Username))

            '        For Each t In tweets
            '            UpdateMessagePost(Acc, t)
            '        Next

            '        EndDownload = tweets.Count <= NumMessFindEnd

            '    Loop

            '    If EndDownload Then
            '        'Acc.Account_Update.Message_Update_Count = Acc.Account_Update.Post_Count
            '        Acc.Account_Update.Message_Update = Date.UtcNow
            '        db.SubmitChanges()
            '    End If

            '    MyApp.WriteAppLog(SF("(tab)(tab)end update message: {0}", Acc.Username))

            'End Sub
            Public Function UpdateMessagePost(Acc As mDB.Account, t As WebApi.Twitter.Tweet) As mDB.Message_Post

                'aggiorna messaggio
                Dim Mess = db.TAB.Message_Post.BY.Message_Post.Post_Code(t.id_str).ToObj

                If Mess Is Nothing Then
                    Mess = New mDB.Message_Post

                    '-------------------------------------------------------------
                    'crea l'account
                    Dim AccCode = t.user.id_str
                    If AccCode <> "" Then
                        Dim MessAcc = mDB.Account.GetForUpdate(AccCode, AccType.TWITTER_ACCOUNT)
                        db.SubmitChanges()
                        Mess.Account_Id = MessAcc.Id
                    Else
                        Mess.Account_Id = 0
                    End If

                    Mess.Parent_Post_Update = t.in_reply_to_status_id_str <> ""

                    '-------------------------------------------------------------
                    'crea alert
                    If Acc.Id <> Mess.Account_Id Then
                        MyApp.AlertAdd(mDB.Alert.Type.MESSAGE, Acc.Id, Mess.Account_Id, t.created_at, t.id_str)
                    End If

                    db.TAB.Message_Post.InsertOnSubmit(Mess)



                End If

                Mess.Post_Code = t.id_str
                If Mess.Account_Id <> Acc.Id Then
                    Mess.To_Account_Id = Acc.Id
                Else
                    Mess.To_Account_Id = 0
                End If
                Mess.To_Account_Id = Acc.Id

                Mess.Post_Text = MyApp.ToUTF8DB(t.text)
                Mess.Pubb_Date = t.created_at
                Mess.Reply_To_Post_Code = t.in_reply_to_status_id_str
                Mess.Is_Share = Mess.Post_Text.StartsWith("RT ")
                Mess.Hash_Id = Mess.Post_Text.GetHashCode

                db.SubmitChanges()

                Return Mess

            End Function

            Public Function UpdatePrivatePost(Acc As mDB.Account, t As WebApi.Twitter.Tweet) As mDB.Private_Post

                'aggiorna messaggio
                Dim Mess = db.TAB.Private_Post.BY.Private_Post.Post_Code(t.id_str).BY.Private_Post.Account_Id(Acc.Id).ToObj

                Dim IsSent = t.sender_id = Acc.Account_Code

                If Mess Is Nothing Then
                    Mess = New mDB.Private_Post

                    '-------------------------------------------------------------
                    'crea l'account
                    Dim AccCode = IIf(IsSent, t.recipient_id, t.sender_id)
                    If AccCode <> "" Then
                        Dim MessAcc = mDB.Account.GetForUpdate(AccCode, AccType.TWITTER_ACCOUNT)
                        db.SubmitChanges()
                        Mess.To_Account_Id = MessAcc.Id
                    Else
                        Mess.To_Account_Id = 0
                    End If

                    '-------------------------------------------------------------
                    'crea alert
                    If Not IsSent Then
                        MyApp.AlertAdd(mDB.Alert.Type.PRIVATE_POST, Acc.Id, Mess.To_Account_Id, t.created_at, t.sender_id)
                    End If

                    db.TAB.Private_Post.InsertOnSubmit(Mess)


                End If

                Mess.Post_Code = t.id_str
                Mess.Account_Id = Acc.Id
                Mess.Is_Sent = IsSent
                Mess.Post_Text = MyApp.ToUTF8DB(t.text)
                Mess.Pubb_Date = t.created_at
                Mess.Hash_Id = Mess.Post_Text.GetHashCode

                db.SubmitChanges()

                'messaggio riepilogo
                'Dim LastType As mDB.Private_Post_Last.type = IIf(IsSend, mDB.Private_Post_Last.type.SEND, mDB.Private_Post_Last.type.RECEIVE)
                Dim LastMess = Acc.Tab_Private_Post_Last(Mess.To_Account_Id, IsSent).ToObj
                If LastMess Is Nothing Then
                    LastMess = New mDB.Private_Post_Last
                    db.TAB.Private_Post_Last.InsertOnSubmit(LastMess)

                    LastMess.Account_Id = Acc.Id
                    LastMess.To_Account_Id = Mess.To_Account_Id
                    LastMess.Is_Sent = IsSent

                End If

                LastMess.Post_Count += 1
                If Mess.Pubb_Date > LastMess.Pubb_Date Then
                    LastMess.Post_Id = Mess.Id
                    LastMess.Pubb_Date = Mess.Pubb_Date
                End If
                db.SubmitChanges()



                Return Mess

            End Function

#End Region

#Region "SHARED"

            'Public Sub UpdateAccountShare(Acc As mDB.Account)

            '    Const NumShareFindEnd = 50
            '    'creo il client con i dati dell'account collegato
            '    Dim tc = New WebApi.Twitter.TwitterClient(Me.oauth)


            '    Dim EndDownload = False
            '    Dim Last_Code = ""


            '    MyApp.WriteAppLog(SF("(tab)(tab)begin update share post: {0}", Acc.Username))

            '    '---------------------------------------------------------------------------
            '    ' verifica i vecchi share post

            '    If Acc.Account_Update.Share_Check_Old Then

            '        Do Until EndDownload

            '            Last_Code = ""
            '            Dim OldShare = db.TAB.SharePost.BY.SharePost.Account_Id(Acc.Id).Limit(1).OrderBy("pubb_date asc").Limit(1).ToObj

            '            'prendo il messaggio + nuovo
            '            If OldShare IsNot Nothing Then
            '                Last_Code = OldShare.Post_Code
            '            End If

            '            Dim tweets As List(Of WebApi.Twitter.Tweet)

            '            Try
            '                tweets = tc.GetMyTweetsRetwitted("", Last_Code)

            '            Catch ex As WebApi.Net.ExceptionRequest

            '                MyApp.WriteAppLog(SF("(tab)(tab)(tab)ExceptionAccessUnauthorized old share post: {0}, {1}", tc.LastError.code, tc.LastError.message))
            '                Exit Do

            '            End Try

            '            MyApp.WriteAppLog(SF("(tab)(tab)(tab)old share post: {0}, {1}", tweets.Count, Acc.Username))

            '            For Each t In tweets
            '                UpdateAccountShare(Acc, t)
            '            Next

            '            EndDownload = tweets.Count <= NumShareFindEnd

            '        Loop

            '        If EndDownload Then
            '            Acc.Account_Update.Share_Check_Old = db.ToBool(False)
            '            db.SubmitChanges()
            '        End If


            '    End If


            '    '---------------------------------------------------------------------------
            '    ' verifica i nuovi share post

            '    EndDownload = False

            '    Do Until EndDownload

            '        Dim First_Code = ""
            '        Dim LastShare = db.TAB.SharePost.BY.SharePost.Account_Id(Acc.Id).Limit(1).OrderBy("pubb_date desc").Limit(1).ToObj

            '        'prendo il messaggio + nuovo
            '        If LastShare IsNot Nothing Then
            '            First_Code = LastShare.Post_Code
            '        End If


            '        Dim tweets As List(Of WebApi.Twitter.Tweet)

            '        Try
            '            tweets = tc.GetMyTweetsRetwitted(First_Code, "")

            '        Catch ex As WebApi.Net.ExceptionRequest

            '            MyApp.WriteAppLog(SF("(tab)(tab)(tab)ExceptionRequest new share post: {0}, {1}", tc.LastError.code, tc.LastError.message))
            '            Exit Do

            '        End Try

            '        MyApp.WriteAppLog(SF("(tab)(tab)(tab)new share post: {0}, {1}", tweets.Count, Acc.Username))

            '        For Each t In tweets
            '            UpdateAccountShare(Acc, t)
            '        Next

            '        EndDownload = tweets.Count <= NumShareFindEnd

            '    Loop

            '    If EndDownload Then
            '        Acc.Account_Update.Share_Update = Date.UtcNow
            '        db.SubmitChanges()
            '    End If

            '    MyApp.WriteAppLog(SF("(tab)(tab)end update share post: {0}", Acc.Username))

            'End Sub
            Public Sub DownloadAccountShares(Acc As mDB.Account)

                Const NumShareFindEnd = 50
                'creo il client con i dati dell'account collegato
                Dim tc = New WebApi.Twitter.TwitterClient(Me.oauth)


                Dim EndDownload = False
                Dim Last_Code = ""


                MyApp.WriteProcLog(SF("(tab)(tab)begin update share post: {0}", Acc.ToString), Task.TaskType.UPDATE_ACCOUNTS)

                '---------------------------------------------------------------------------
                ' verifica tutti i share post

                Last_Code = ""
                Do Until EndDownload

                    Dim tweets As List(Of WebApi.Twitter.Tweet)

                    'Try
                    tweets = tc.GetMyTweetsRetwitted("", Last_Code)

                    'Catch ex As WebApi.Net.ExceptionAPIResponse

                    '    MyApp.WriteProcLog(SF("(tab)(tab)(tab)ExceptionAccessUnauthorized share post: {0}, {1}", tc.LastError.Code, tc.LastError.Message), Task.TaskType.UPDATE_ACCOUNTS)
                    '    Exit Do

                    'End Try

                    MyApp.WriteProcLog(SF("(tab)(tab)(tab)share post: {0}, {1}", tweets.Count, Acc.Username), Task.TaskType.UPDATE_ACCOUNTS)

                    For Each t In tweets
                        Me.UpdateSharePost(Acc, t)
                    Next

                    If tweets.Count > 0 Then
                        Last_Code = tweets.Last.id_str
                    End If

                    EndDownload = tweets.Count <= NumShareFindEnd

                Loop

                If EndDownload Then
                    Acc.Account_Update.Share_Update = Date.UtcNow
                    db.SubmitChanges()
                End If

                MyApp.WriteProcLog(SF("(tab)(tab)end update share post: {0}", Acc.Username), Task.TaskType.UPDATE_ACCOUNTS)

            End Sub
            Public Function UpdateSharePost(Acc As mDB.Account, t As WebApi.Twitter.Tweet) As mDB.Share_Post

                'aggiorna share post
                Dim Share = mDB.Share_Post.GetForUpdate(t.id_str)

                If Acc.Account_Code = t.user.id_str Then
                    Share.Account_Id = Acc.Id
                Else
                    Share.Account_Id = 0
                End If
                Share.Post_Text = MyApp.ToUTF8DB(t.text) ' Encoding.Default.GetString(Encoding.Convert(Encoding.UTF8, Encoding.Default, Encoding.UTF8.GetBytes(t.text)))
                Share.Pubb_Date = t.created_at
                Share.Share_Det_Update = Share.Share_Det_Count <> t.retweet_count
                Share.Share_Det_Count = t.retweet_count
                Share.Hash_Id = Share.Post_Text.GetHashCode

                db.SubmitChanges()

                Return Share

            End Function
            Public Sub DownloadSharePostDetails(p As mDB.Share_Post)
                Dim tc As WebApi.Twitter.TwitterClient
                Dim EndDownload = False

                Dim tweets As List(Of WebApi.Twitter.Tweet)


                Do
                    Dim UserAcc = mDB.Account_Auth.GetUserAccountAvailable(mDB.Account_Auth.ServiceType.SHARE_POST, AccType.TWITTER_ACCOUNT)

                    Try

                        If UserAcc IsNot Nothing Then
                            Me.oauth = UserAcc.getOauth

                        Else

                            'MyApp.WriteAppLog(SF("(tab)(tab)error update share details: user account not Available"))
                            Throw New WebApi.Net.ExceptionTooManyRequestsAllAccount

                        End If

                        tc = New WebApi.Twitter.TwitterClient(Me.oauth)
                        tweets = tc.GetRetweetsOfTweet(p.Post_Code)

                        MyApp.WriteProcLog(SF("(tab)(tab)(tab)update share details: {0}, {1}", tweets.Count, p.Post_Code), Task.TaskType.UPDATE_ACCOUNTS)

                        For Each t In tweets
                            UpdateSharePostDetail(p, t)
                        Next

                        EndDownload = True

                    Catch ex As WebApi.Net.ExceptionAPITooManyRequests

                        MyApp.WriteProcLog(SF("(tab)(tab)error update share details: ExceptionAPITooManyRequests: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), Task.TaskType.UPDATE_ACCOUNTS)
                        UserAcc.SetLastRateLimit(mDB.Account_Auth.ServiceType.SHARE_POST)

                    Catch ex As WebApi.Net.ExceptionAPIAccount

                        MyApp.WriteProcLog(SF("(tab)(tab)(tab)error update share details: ExceptionAPIAccount: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), Task.TaskType.UPDATE_ACCOUNTS)
                        UserAcc.SetLastRateLimit(mDB.Account_Auth.ServiceType.SHARE_POST)

                    End Try

                Loop Until EndDownload

                If EndDownload Then
                    'p.Share_Det_Update_Count = p.Share_Det_Count
                    'p.Share_Det_Update = Date.UtcNow
                    p.Share_Det_Update = False
                    db.SubmitChanges()
                End If

            End Sub
            Public Function UpdateSharePostDetail(p As mDB.Share_Post, t As WebApi.Twitter.Tweet) As mDB.Share_Detail

                'aggiorna share post
                Dim ShareDet = db.TAB.Share_Detail.BY.Share_Detail.Post_Code(t.id_str).ToObj

                If ShareDet Is Nothing Then
                    ShareDet = New mDB.Share_Detail

                    '-------------------------------------------------------------
                    'crea l'account
                    Dim AccCode = t.user.id_str

                    Dim ShareAcc = mDB.Account.GetForUpdate(AccCode, AccType.TWITTER_ACCOUNT)
                    db.SubmitChanges()

                    ShareDet.Account_Id = ShareAcc.Id

                    db.InsertOnSubmit(ShareDet)

                End If

                ShareDet.To_Account_Id = p.Account_Id
                ShareDet.Share_Post_Id = p.Id
                ShareDet.Post_Code = t.id_str
                ShareDet.Pubb_Date = t.created_at

                ' cosa fare con l'accont
                'ShareDet.Account_Id = Acc.Id


                db.SubmitChanges()

                Return ShareDet

            End Function

#End Region

#Region "FAVORITES"


            Public Sub DownloadAccountFavoritePosts(Acc As mDB.Account)

                Const NumMessFindEnd = 100
                'creo il client con i dati dell'account collegato
                Dim tc = New WebApi.Twitter.TwitterClient(Me.oauth)

                Dim EndDownload = False
                Dim ContinuePrevDownload = False
                Dim Since_id = ""
                Dim Max_id = ""

                Dim Codes = Acc.Account_Update.Favorite_Post_Last_Code.ToString.Split(",")

                If Codes.Length > 1 Then
                    ContinuePrevDownload = True
                    Since_id = Codes(0)
                    Max_id = Codes(1)
                Else
                    Since_id = Acc.GetLastFavoritePostCode ' Me.GetLastMessCod(Acc)
                End If

                MyApp.WriteProcLog(SF("(tab)(tab)TWITTER begin update favorite post: {0} ({1})", Acc.Fullname, Acc.Username), Task.TaskType.UPDATE_ACCOUNTS)

                EndDownload = False
                Do Until EndDownload

                    Dim tweets As List(Of WebApi.Twitter.Tweet)

                    'Try

                    tweets = tc.GetFavorites("", Acc.Account_Code, Since_id, Max_id)

                    'Catch ex As WebApi.Net.ExceptionAPIResponse

                    '    'MyApp.WriteProcLog(SF("(tab)(tab)(tab)ExceptionRequest message: {0}, {1}", tc.LastError.Code, tc.LastError.Message), AutoProcType.UPDATE_ACCOUNTS)
                    '    Exit Do

                    'End Try

                    MyApp.WriteProcLog(SF("(tab)(tab)(tab)favorite post: {0}, {1}", tweets.Count, Acc.Username), Task.TaskType.UPDATE_ACCOUNTS)

                    For Each t In tweets
                        UpdateFavoritePost(Acc, t)
                    Next

                    If tweets.Count > 0 Then
                        Max_id = tweets.Last.id_str
                    End If

                    Acc.Account_Update.Favorite_Post_Last_Code = SF("{0},{1}", Since_id, Max_id)
                    db.SubmitChanges()

                    EndDownload = tweets.Count <= NumMessFindEnd

                    If EndDownload And ContinuePrevDownload Then
                        ContinuePrevDownload = False
                        EndDownload = False
                        Since_id = Acc.GetLastFavoritePostCode ' Me.GetLastMessCod(Acc)
                        Max_id = ""
                    End If

                Loop

                If EndDownload Then
                    Acc.Account_Update.Favorite_Post_Update = Date.UtcNow
                    Acc.Account_Update.Favorite_Post_Last_Code = ""
                    db.SubmitChanges()
                End If

                MyApp.WriteProcLog(SF("(tab)(tab)end update favorite post: {0} ({1})", Acc.Fullname, Acc.Username), Task.TaskType.UPDATE_ACCOUNTS)

            End Sub

            ' *** TODO ***
            Public Function UpdateFavoritePost(Acc As mDB.Account, t As WebApi.Twitter.Tweet) As mDB.Favorite_Post

                'aggiorna favorito
                Dim Favorite = mDB.Favorite_Post.GetForUpdate(Acc.Id, t.id_str)

                Favorite.Post_Text = MyApp.ToUTF8DB(t.text)
                Favorite.Pubb_Date = t.created_at

                db.SubmitChanges()

                Return Favorite

            End Function

            ' *** TODO ***
            Public Function AddFavoritePost(Acc As mDB.Account, PostCode As String) As mDB.Favorite_Post

                Dim tweet As WebApi.Twitter.Tweet = Nothing
                Dim tc = New WebApi.Twitter.TwitterClient(Me.oauth)

                Try
                    tweet = tc.PostFavoritesCreate(PostCode)
                Catch ex As Exception

                End Try

                If tweet IsNot Nothing Then

                    Return Me.UpdateFavoritePost(Acc, tweet)

                    'Return Acc.AddFavoritePost(PostCode)

                Else
                    Return Nothing
                End If


            End Function


            Public Sub RemoveFavoritePost(Acc As mDB.Account, PostCode As String)

                Dim tweet As WebApi.Twitter.Tweet = Nothing
                Dim tc = New WebApi.Twitter.TwitterClient(Me.oauth)

                Try
                    tweet = tc.PostFavoritesDestroy(PostCode)
                Catch ex As Exception

                End Try

                If tweet IsNot Nothing Then
                End If

            End Sub



#End Region



#Region "QUERY"
            Public Sub DownloadQueryPostsAsync(param As Object)

                Try

                    HttpContext.Current = Me.HttpContextCurrent
                    Me.db = mDB.GetDB '(False)

                    Dim QueryId As Integer = param.queryid
                    Dim Mode As mDB.Query.UpdateModeType = param.mode

                    'Me.ex = Nothing

                    Dim query = db.TAB.Query.GetByPK(QueryId)

                    Dim EndDownload = False
                    Do

                        Dim UserAcc = mDB.Account_Auth.GetUserAccountAvailable(mDB.Account_Auth.ServiceType.SEARCH, AccType.TWITTER_ACCOUNT)

                        Try

                            If UserAcc IsNot Nothing Then
                                Me.oauth = UserAcc.getOauth

                                Dim NewQuery = query.Post_Download_Count = -1

                                MyApp.WriteProcLog(SF("(tab)(tab)download query: '{0}'", query.Query), Task.TaskType.UPDATE_QUERY)
                                Me.DownloadQueryPosts(query, Mode)

                                If Mode = mDB.Query.UpdateModeType.NORMAL Then
                                    'IMPORTANTE se è una quesry in listen prima di indicizzare salva gli account in una lista
                                    If query.Tab_Listen_Query.ToObj IsNot Nothing Then
                                        MyApp.WriteProcLog(SF("(tab)(tab)add account query relatime: '{0}'", query.Query), Task.TaskType.UPDATE_QUERY)

                                        Dim q = db.GetQuery

                                        q.Sql("" &
                                            "insert into " & query.ArchiveAccount.Table_Name & " " &
                                                "(query_id, account_code,post_update,post_count, account_username,account_follower_count ) " &
                                            "select " &
                                                query.Id.ToString & ", account_code, DATE(pubb_date),1,account_username, account_follower_count " &
                                            "from " & query.ArchivePost.Table_Name & " where query_id =" & q.P(query.Id) & " and pubb_date >" & q.P(query.Last_Update) & " " &
                                            "ON DUPLICATE KEY UPDATE post_count = post_count + VALUES(post_count) " &
                                        "").ExecuteCommand()

                                        Dim lastrow = query._Tab_Query_Account.OrderBy("post_update desc").Limit(1, 10000).ToObj
                                        If lastrow IsNot Nothing Then
                                            MyApp.WriteProcLog(SF("(tab)(tab)(tab)delete account: '{0}'", query.Query), Task.TaskType.UPDATE_QUERY)
                                            query.
                                                _Tab_Query_Account.
                                                Where("post_update", "<", lastrow.Post_Update).
                                            Delete.ExecuteCommand()
                                        End If

                                    End If

                                    ' IMPOERTANTE lo metto qui perchè qui sono sicuro che posso indicizzare che ha finito di scaricare tutti i post
                                    MyApp.WriteProcLog(SF("(tab)(tab)indicizza query: '{0}'", query.Query), Task.TaskType.UPDATE_QUERY)
                                    Task.Elaborate.CreateIndexQueryPosts(query.Id)

                                    ' accondo di spedire una mail
                                    If NewQuery Then
                                        MyApp.Email.System.Queued(Email.System.Type.QUERY_DOWNLOADED, False, New With {.query_id = query.Id})
                                    End If


                                End If

                            Else

                                MyApp.WriteProcLog(SF("(tab)(tab)error update query post: user account not Available"), Task.TaskType.UPDATE_QUERY)
                                Throw New WebApi.Net.ExceptionTooManyRequestsAllAccount

                            End If

                            EndDownload = True

                        Catch ex As WebApi.Net.ExceptionAPITooManyRequests

                            MyApp.WriteProcLog(SF("(tab)(tab)error update query post: ExceptionAPITooManyRequests: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), Task.TaskType.UPDATE_QUERY)
                            UserAcc.SetLastRateLimit(mDB.Account_Auth.ServiceType.SEARCH)

                        Catch ex As WebApi.Net.ExceptionAPIAccount

                            MyApp.WriteProcLog(SF("(tab)(tab)error update query post: ExceptionAPIAccount: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), Task.TaskType.UPDATE_QUERY)
                            UserAcc.SetLastRateLimit(mDB.Account_Auth.ServiceType.SEARCH)


                        Catch ex As WebApi.Net.ExceptionAPIResponse
                            MyApp.WriteProcLog(SF("(tab)(tab)error update query post: ExceptionAPIResponse: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), Task.TaskType.UPDATE_QUERY)

                            'Catch ex As Exception

                            '    HttpContext.Current.Items("Exception_UpdateQuery") = ex
                            '    EndDownload = True

                        End Try

                    Loop Until EndDownload

                Catch ex As Exception

                    HttpContext.Current.Items("Exception_UpdateQuery") = ex

                End Try

            End Sub
            'Public Sub DownloadQueryPostsAsyncRealTime(QueryId As Integer)

            '    HttpContext.Current = Me.HttpContextCurrent
            '    Me.db = mDB.GetDB(False)
            '    'Me.ex = Nothing

            '    Dim query = db.TAB.Query.GetByPK(QueryId)

            '    Dim EndDownload = False
            '    Do

            '        Dim UserAcc = Me.GetUserAccountAvailable(mDB.User_Account.ServiceType.SEARCH)

            '        Try

            '            If UserAcc IsNot Nothing Then
            '                Me.oauth = UserAcc.getOauth

            '                MyApp.WriteProcLog(SF("(tab)(tab)download query: '{0}'", query.Query), AutoProcType.UPDATE_QUERY)
            '                DownloadQueryPosts(query)

            '                MyApp.WriteProcLog(SF("(tab)(tab)indicizza query: '{0}'", query.Query), AutoProcType.UPDATE_QUERY)

            '                ' IMPOERTANTE lo metto qui perchè qui sono sicuro che posso indicizzare che ha finito di scaricare tutti i post
            '                'Data.Elaborate.IndexQuery(query.Id)
            '            Else

            '                MyApp.WriteProcLog(SF("(tab)(tab)error update query post: user account not Available"), AutoProcType.UPDATE_QUERY)
            '                Throw New WebApi.Net.ExceptionTooManyRequestsAllAccount

            '            End If

            '            EndDownload = True

            '        Catch ex As WebApi.Net.ExceptionTooManyRequests

            '            MyApp.WriteProcLog(SF("(tab)(tab)error update query post: ExceptionTooManyRequests: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), AutoProcType.UPDATE_QUERY)
            '            UserAcc.SetLastRateLimit(mDB.User_Account.ServiceType.SEARCH)

            '        Catch ex As WebApi.Net.ExceptionAccount

            '            MyApp.WriteProcLog(SF("(tab)(tab)error update query post: ExceptionAccount: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), AutoProcType.UPDATE_QUERY)
            '            UserAcc.SetLastRateLimit(mDB.User_Account.ServiceType.SEARCH)

            '        Catch ex As Exception

            '            HttpContext.Current.Items("Exception_UpdateQuery") = ex
            '            EndDownload = True

            '        End Try

            '    Loop Until EndDownload




            'End Sub

            'Public Function GetLastQueyPostCod(q As mDB.Query) As String


            '    Dim LastPost = db.TAB.Query_Post.BY.Query_Post.Query_Id(q.Id).OrderBy("pubb_date desc").Limit(1).ToObj
            '    'prendo il post + nuovo
            '    If LastPost IsNot Nothing Then
            '        Return LastPost.Post_Code
            '    Else
            '        Return ""
            '    End If

            'End Function


            Public Sub DownloadQueryPosts(q As mDB.Query, Mode As mDB.Query.UpdateModeType)
                Dim NumPostFindEnd = 50
                Dim NumPostToDownload = 2000
                Dim MaxPostToDownload = 3000

                If Mode = GloukDB.Query.UpdateModeType.REALTIME Then
                    NumPostToDownload = 100
                    MaxPostToDownload = 150
                End If

                Dim tc = New WebApi.Twitter.TwitterClient(Me.oauth)

                Dim EndDownload = False
                Dim ContinuePrevDownload = False
                Dim Since_id = ""
                Dim Max_id = ""
                Dim ResultType = ""

                Dim PostCount = 0
                Dim PostTotal = 0

                ' imposto i codici da cui partire
                Dim Codes = q.Post_Last_Code.ToString.Split(",")

                If Codes.Length > 1 Then
                    ContinuePrevDownload = True
                    Since_id = Codes(0)
                    Max_id = Codes(1)
                Else
                    Since_id = q.GetLastPostCode ' Me.GetLastQueyPostCod(q)
                End If

                'imposto la query
                Dim query As String = q.Query
                Dim geocode As String = ""
                Dim Lang As String = ""

                If q.Place_Id > 0 Then
                    Dim place = db.TAB.Place.GetByPK(q.Place_Id)
                    geocode = SF("{0},{1},{2}", DBase.Conv.DoubleToDB(place.Lat), DBase.Conv.DoubleToDB(place.Lon), "15mi")
                End If
                If q.Lang_Code <> "" Then
                    Lang = q.Lang_Code
                End If

                'If Mode = mDB.Query.UpdateModeType.REALTIME Then
                '    ResultType = "recent"
                'End If
                ResultType = "recent"

                Do Until EndDownload

                    Dim tweets = tc.GetSearch(query, Since_id, Max_id, ResultType, geocode, Lang)

                    For Each t In tweets.statuses

                        If Not t.text.StartsWith("RT ") Then
                            Me.UpdateQueryPost(q, t)
                            PostCount += 1
                        End If

                    Next

                    PostTotal += tweets.statuses.Count

                    MyApp.WriteProcLog(SF("(tab)(tab)(tab)update query: '{0}' - add:{1}, dwn:{2}'", q.Query, PostCount, PostTotal), Task.TaskType.UPDATE_QUERY)

                    If tweets.statuses.Count > 0 Then
                        Max_id = tweets.statuses.Last.id_str
                    End If

                    q.Post_Last_Code = SF("{0},{1}", Since_id, Max_id)
                    db.SubmitChanges()


                    If tweets.statuses.Count < NumPostFindEnd Or PostCount >= NumPostToDownload Or PostTotal >= MaxPostToDownload Then
                        EndDownload = True
                    End If

                    If EndDownload And ContinuePrevDownload Then
                        ContinuePrevDownload = False
                        EndDownload = False
                        PostCount = 0
                        Since_id = q.GetLastPostCode ' Me.GetLastQueyPostCod(q)
                        Max_id = ""
                    End If


                Loop

                If EndDownload Then
                    q.Post_Download_Count = PostCount
                    q.Post_Last_Code = ""
                    db.SubmitChanges()
                End If

            End Sub
            'Public Sub DownloadQueryPostsRealTime(q As mDB.Query)
            '    Const NumPostFindEnd = 50
            '    Const NumPostToDownload = 2000

            '    Dim tc = New WebApi.Twitter.TwitterClient(Me.oauth)

            '    Dim EndDownload = False
            '    Dim ContinuePrevDownload = False
            '    Dim Since_id = ""
            '    Dim Max_id = ""

            '    Dim PostCount = 0

            '    ' imposto i codici da cui partire
            '    Dim Codes = q.Post_Last_Code.ToString.Split(",")

            '    If Codes.Length > 1 Then
            '        ContinuePrevDownload = True
            '        Since_id = Codes(0)
            '        Max_id = Codes(1)
            '    Else
            '        Since_id = Me.GetLastQueyPostCod(q)
            '    End If

            '    'imposto la query
            '    Dim query As String = q.Query
            '    Dim geocode As String = ""
            '    Dim Lang As String = ""

            '    If q.Place_Id > 0 Then
            '        Dim place = db.TAB.Place.GetByPK(q.Place_Id)
            '        geocode = SF("{0},{1},{2}", DBase.Conv.DoubleToDB(place.Lat), DBase.Conv.DoubleToDB(place.Lon), "15mi")
            '    End If
            '    If q.Lang_Code <> "" Then
            '        Lang = q.Lang_Code
            '    End If

            '    Do Until EndDownload

            '        Dim tweets = tc.GetSearch(query, Since_id, Max_id, "recent", geocode, Lang)

            '        For Each t In tweets.statuses

            '            If Not t.text.StartsWith("RT ") Then
            '                Me.UpdateQueryPost(q, t)
            '                PostCount += 1
            '            End If

            '        Next

            '        MyApp.WriteProcLog(SF("(tab)(tab)(tab)update query: {0} - '{1}'", PostCount, q.Query), AutoProcType.UPDATE_QUERY)

            '        If tweets.statuses.Count > 0 Then
            '            Max_id = tweets.statuses.Last.id_str
            '        End If

            '        q.Post_Last_Code = SF("{0},{1}", Since_id, Max_id)
            '        db.SubmitChanges()


            '        If tweets.statuses.Count < NumPostFindEnd Or PostCount > NumPostToDownload Then
            '            EndDownload = True
            '        End If

            '        If EndDownload And ContinuePrevDownload Then
            '            ContinuePrevDownload = False
            '            EndDownload = False
            '            PostCount = 0
            '            Since_id = Me.GetLastQueyPostCod(q)
            '            Max_id = ""
            '        End If


            '    Loop

            '    If EndDownload Then
            '        q.Post_Download_Count = PostCount
            '        q.Post_Last_Code = ""
            '        db.SubmitChanges()
            '    End If

            'End Sub

            Public Function UpdateQueryPost(query As mDB.Query, t As WebApi.Twitter.Tweet) As mDB._Query_Post

                'aggiorna post
                'Dim Post = db.TAB.Query_Post.BY.Query_Post.Query_Id(query.Id, t.id_str).ToObj
                Dim Post = query._Tab_Query_Post.BY._Query_Post._Post_Code(t.id_str).ToObj

                If Post Is Nothing Then
                    Post = New mDB._Query_Post
                    db.InsertOnSubmit(query.ArchivePost.Table_Name, Post)
                End If

                Post.Query_Id = query.Id
                Post.Post_Code = t.id_str
                Post.Post_Text = MyApp.ToUTF8DB(t.text) 'Encoding.Default.GetString(Encoding.Convert(Encoding.UTF8, Encoding.Default, Encoding.UTF8.GetBytes(t.text)))
                Post.Pubb_Date = t.created_at


                Post.Share_Count = t.retweet_count

                If t.user IsNot Nothing Then
                    Post.Account_Code = t.user.id_str
                    Post.Account_Username = t.user.screen_name
                    Post.Account_Follower_Count = t.user.followers_count
                End If

                If t.entities IsNot Nothing Then
                    If t.entities.media IsNot Nothing Then
                        If t.entities.media.Count > 0 Then
                            Post.Image_Url = t.entities.media(0).media_url
                            'Post.Image_Code = t.entities.media(0).id_str
                            'Post.Image_Source_Code = t.entities.media(0).source_status_id_str
                        End If
                    End If
                End If

                db.SubmitChanges()

                Return Post

            End Function

#End Region

#Region "FOLLOW"


            Public Function DownloadRelationships(ids As List(Of String)) As Dictionary(Of String, Dictionary(Of String, String))
                Dim tc = New WebApi.Twitter.TwitterClient(Me.oauth)
                Dim NumUserPerRequest = 50
                Dim Rel As New Dictionary(Of String, Dictionary(Of String, String))


                Dim page = Int((ids.Count - 1) / NumUserPerRequest) + 1

                For ct = 1 To page

                    Dim Numids = NumUserPerRequest
                    If ct = page Then
                        Numids = ids.Count - ((page - 1) * NumUserPerRequest)
                    End If

                    Dim AccRels = tc.GetFriendshipsLookup("", String.Join(",", ids.GetRange((ct - 1) * NumUserPerRequest, Numids)))

                    MyApp.WriteProcLog(SF("(tab)(tab)update relation number user: {0}", Numids), Task.TaskType.AUTO_FOLLOW)

                    For Each AccRel In AccRels
                        For Each conn In AccRel.connections
                            If Not Rel.ContainsKey(conn) Then
                                Rel.Add(conn, New Dictionary(Of String, String))
                            End If
                            Rel(conn).Add(AccRel.id_str, "")
                        Next
                    Next

                Next

                Return Rel

            End Function

            Public Function FollowAccont(Acc As mDB.Account, AccountCode As String) As String

                Dim ErrorCode = 0
                Dim tc As New WebApi.Twitter.TwitterClient(Me.oauth)
                tc.AutoProc = Task.TaskType.AUTO_FOLLOW

                Dim User As WebApi.Twitter.User = Nothing

                User = New WebApi.Twitter.User ' *DEBUG* tc.PostFriendshipsCreate("", AccountCode)

                If User Is Nothing Then
                    Return ""
                Else
                    Acc.AddAccountLink(mDB._Account_Link.Type.FRIENDS, AccountCode, MyApp.Network.AccType.TWITTER_ACCOUNT)
                    Return User.id_str
                End If


            End Function

            Public Function UnFollowAccont(Acc As mDB.Account, AccountCode As String) As String

                Dim tc As New WebApi.Twitter.TwitterClient(Me.oauth)
                tc.AutoProc = Task.TaskType.AUTO_FOLLOW

                Dim User As WebApi.Twitter.User = Nothing

                User = New WebApi.Twitter.User ' *DEBUG* tc.PostFriendshipsDestroy("", AccountCode)

                If User Is Nothing Then
                    Return ""
                Else
                    Acc.RemoveAccountLink(mDB._Account_Link.Type.FRIENDS, AccountCode)
                    Return User.id_str
                End If

            End Function
#End Region

#Region "PLACE"

            Public Sub DownloadPlace(Acc As mDB.Account)
                Dim tc As WebApi.Twitter.TwitterClient
                Dim EndDownload = False


                Do
                    Dim UserAcc = mDB.Account_Auth.GetUserAccountAvailable(mDB.Account_Auth.ServiceType.SHARE_POST, AccType.TWITTER_ACCOUNT)

                    Try

                        If UserAcc IsNot Nothing Then
                            Me.oauth = UserAcc.getOauth
                        Else
                            Throw New WebApi.Net.ExceptionTooManyRequestsAllAccount
                        End If

                        tc = New WebApi.Twitter.TwitterClient(Me.oauth)
                        Dim p As WebApi.Twitter.GeoResponse = Nothing
                        If Acc.Location.Trim <> "" Then
                            p = tc.GetGeoSearch(Acc.Location)
                        End If

                        UpdateAccountPlaces(Acc, p)

                        EndDownload = True

                    Catch ex As WebApi.Net.ExceptionAPI

                        MyApp.WriteProcLog(SF("(tab)(tab)error update place: ExceptionAPI: {0}, {1}", ex.ServiceError.Code, ex.ServiceError.Message), Task.TaskType.UPDATE_ACCOUNTS)
                        UserAcc.SetLastRateLimit(mDB.Account_Auth.ServiceType.SHARE_POST)



                    End Try
                Loop Until EndDownload

                If EndDownload Then

                End If

            End Sub
            Public Sub UpdateAccountPlaces(Acc As mDB.Account, p As WebApi.Twitter.GeoResponse)


                Dim SelectPlaceName As String = "Nothing"
                Dim selectplace As mDB.Place = Nothing

                Acc.Account_Add_Info.Place_Id = -1

                If p IsNot Nothing Then
                    If p.result.places.Count > 0 Then

                        Dim country = p.result.places(0).country_code
                        Dim name = p.result.places(0).name

                        Dim TempPlace As mDB.Place ' As WebApi.Twitter.Place = p.result.places(0)
                        Dim Primo = True
                        For Each place In p.result.places

                            TempPlace = UpdatePlace(place)

                            If Primo Or (place.name = name And place.place_type = "city" And place.country_code = country) Then
                                selectplace = TempPlace
                                'Exit For
                            End If

                            Primo = False
                        Next

                        If selectplace IsNot Nothing Then
                            SelectPlaceName = selectplace.Name
                            Acc.Account_Add_Info.Place_Id = selectplace.Id
                        End If
                    End If
                End If

                db.SubmitChanges()

                MyApp.WriteProcLog(SF("(tab)(tab)update place: {0}, place: {1}", Acc.Fullname, SelectPlaceName), Task.TaskType.UPDATE_ACCOUNTS)




            End Sub
            Public Function UpdatePlace(place As WebApi.Twitter.Place) As mDB.Place

                Dim p = db.TAB.Place.BY.Place.Place_Code(place.id).ToObj

                If p Is Nothing Then
                    p = New mDB.Place
                    db.TAB.Place.InsertOnSubmit(p)
                End If

                p.Place_Code = place.id
                p.Name = place.name
                p.Place_Type = place.place_type
                p.Country_Code = place.country_code

                If place.bounding_box IsNot Nothing Then
                    If place.bounding_box.coordinates.Count > 0 Then
                        p.Bounding_Box = MyApp.JSONSerialize(place.bounding_box.coordinates(0))
                    End If
                End If

                If place.contained_within IsNot Nothing Then
                    If place.contained_within.Count > 0 Then
                        Dim pp = UpdatePlace(place.contained_within(0))
                    End If
                End If

                db.SubmitChanges()

                Return p

            End Function

#End Region




            'Public Sub UpdateUserPosts(Acc As mDB.Account)
            '    Const NumPostFindEnd = 100
            '    'creo il client con i dati dell'account collegato
            '    Dim tc = New WebApi.Twitter.TwitterClient(oauth)

            '    '---------------------------------------------------------------------------
            '    'prima verifica tutti i post vecchi

            '    'prendo l'ulmito cursor
            '    Dim Last_Code = Acc.Post_Last_Code

            '    If Last_Code = "-1" Then
            '        Last_Code = ""
            '        Dim OldPost = db.TabPost.Where("account_id", "=", Acc.Id).OrderBy("pubb_date asc").Limit(1).ToObj

            '        'prendo il post + nuovo
            '        If OldPost IsNot Nothing Then
            '            Last_Code = OldPost.Post_Code
            '        End If

            '    End If


            '    Do Until Last_Code = "0"


            '        Dim tweets = tc.GetTweets("", Acc.Account_Code, "", Last_Code)

            '        For Each t In tweets

            '            UpdatePost(Acc, t)

            '            Last_Code = t.id_str

            '        Next

            '        If tweets.Count <= NumPostFindEnd Then
            '            Last_Code = "0"
            '        End If

            '        'aggiorno ultimo codice del post
            '        Acc.Post_Last_Code = Last_Code
            '        db.SubmitChanges()

            '    Loop

            '    '---------------------------------------------------------------------------
            '    ' verifica i nuovi post

            '    Dim First_Code = ""
            '    Dim LastPost = db.TabPost.Where("account_id", "=", Acc.Id).OrderBy("pubb_date desc").Limit(1).ToObj

            '    'prendo il post + nuovo
            '    If LastPost IsNot Nothing Then
            '        First_Code = LastPost.Post_Code
            '    End If

            '    Do Until First_Code = "0"

            '        Dim tweets = tc.GetTweets("", Acc.Account_Code, First_Code, "")

            '        If tweets.Count > 0 Then
            '            First_Code = tweets(0).id_str
            '        End If

            '        For Each t In tweets
            '            UpdatePost(Acc, t)
            '        Next

            '        If tweets.Count <= NumPostFindEnd Then
            '            First_Code = "0"
            '        End If

            '    Loop

            '    If First_Code = "0" Then
            '        Acc.Post_Update_Count = Acc.Post_Count
            '        Acc.Post_Update_Date = Date.UtcNow
            '        db.SubmitChanges()
            '    End If

            'End Sub


            'Private Function SetNewAccount(Acc As mDB.Account) As mDB.Account

            '    Acc.NetworkId = App.NetworkType.TWITTER
            '    'Acc.Post_Update_Date = Utils.Conv.ToTimeStampDate(1)
            '    'Acc.Profile_Update = Utils.Conv.ToTimeStampDate(1)
            '    'Acc.Post_Check_Old = db.ToBool(True)

            '    Return Acc

            'End Function

        End Class
    End Namespace
End Namespace

